export default class Paginate {

    total = 0;
    size = 20;
    defaultSize = 20;
    current = 1;
    searchCount = true;
    pages = 0;
    toPage = 1;
    records = [];
    changeCallBack = new Function();
    asc = '';
    desc = '';
    /** @type ezm-scroll-box **/
    scrollInstance = null;

    /**
     * 构造函数
     * @param changeCallBack    刷新页面回调函数
     * @param size  每页数量
     */
    constructor(changeCallBack = null, size = 20) {
        this.changeCallBack = changeCallBack;
        this.size = size || 20;
        this.defaultSize = size || 20;
    }

    /**
     * 将服务器返回信息写入本对象
     * @param resp  服务器返回
     * @returns {Paginate}
     */
    setResponse(resp) {
        this.total = resp.total;
        this.size = resp.size;
        this.current = resp.current;
        this.pages = resp.pages;
        this.records = resp.records;
        return this;
    }


    /**
     * 重置页面信息
     * 回到第一页
     * @returns {Paginate}
     */
    resetPage() {
        this.current = 1;
        this.size = this.defaultSize;
        this.toPage = 1;
        this.total = 0;
        return this;
    }

    getRequestParams() {
        return {
            size: this.size,
            current: this.toPage,
        }
    }

    fetchRefreshList() {
        this.toPage = 1;
        this.changeCallBack(true);
    }

    fetchMoreNextPage() {
        this.setNextPage();
        this.changeCallBack(false);
    }

    setNextPage(page = null) {
        this.toPage = page || (this.current + 1);
    }

    finishLoading(resp = null) {
        if (resp) this.setResponse(resp);
        if (!this.scrollInstance) return;
        this.scrollInstance.finishPullDown();
        this.scrollInstance.finishPullUp(resp ? resp.records.length < resp.size : false);
        setTimeout(() => this.scrollInstance.scroll.refresh());
    }

    autoPullDown() {
        if (this.scrollInstance) this.scrollInstance.autoPullDown();
    }
}